//
//  AuthContactContentView.swift
//  认证 - 联系人信息内容 View
//
//  Created by 千策万划-mini on 2025/5/7.
//

import Foundation
import ContactsUI

class AuthContactContentView: UIView {
    
    var modelDetail: ModelAuthContactInfo = ModelAuthContactInfo()
    var blockUpdataModel:((ModelAuthContactInfo) -> Void)?
    
    // MARK: - lazy
    lazy var imageScheduleBg: UIImageView = {
        let result = UIImageView()
        result.image = UIImage(named: "icon_auth_schedule_bg")
        result.widthHeight = XY(SCREEN_WIDTH-W(15)*2, W(68))
        return result
    }()
    lazy var imageSchedule: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(W(329), W(38))
        return result
    }()
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.widthHeight = XY(SCREEN_WIDTH, 0)
        self.backgroundColor = .clear
        
        self.addSubView()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 添加
    func addSubView() {
        addSubview(imageScheduleBg)
        imageScheduleBg.addSubview(imageSchedule)
        resetView()
    }
    
    // MARK: - 重置界面
    func resetView(model: ModelAuthContactInfo = ModelAuthContactInfo()) {
        modelDetail = model
        imageScheduleBg.centerXTop = XY(SCREEN_WIDTH/2, W(16))
        let count = GlobalMethod.readInt(forKey: LOCAL_AUTH_PRODUCT_COUNT)
        imageSchedule.image = UIImage(named: count == 5 ? "icon_auth_schedule_4_5" : "icon_auth_schedule_4_4")
        imageSchedule.centerXCenterY = XY(imageScheduleBg.width/2, imageScheduleBg.height/2)
        
        var topMark = imageScheduleBg.bottom
        if !model.mischief.teasing.isEmpty {
            subviews.forEach { subview in
                if subview.tag >= 100 {
                    subview.removeFromSuperview()
                }
            }
            for i in 0..<model.mischief.teasing.count {
                let modelItem = model.mischief.teasing[i]
                let view = AuthContactContentItemView()
                view.tag = 100+i
                view.viewRelation.pickerView.blockConfirmClick = { [weak self](value, code) in
                    guard let self = self else { return }
                    self.modelDetail.mischief.teasing[i].imagine = code
                    self.modelDetail.mischief.teasing[i].relationText = value
                    view.resetView(model: self.modelDetail.mischief.teasing[i])
                    if let block = blockUpdataModel {
                        block(self.modelDetail)
                    }
                }
                view.blockNamePhoneClick = { [weak self](name, phone) in
                    guard let self = self else { return }
                    self.modelDetail.mischief.teasing[i].cautiously = name
                    self.modelDetail.mischief.teasing[i].racing = phone
                    view.resetView(model: self.modelDetail.mischief.teasing[i])
                    if let block = blockUpdataModel {
                        block(self.modelDetail)
                    }
                }
                view.resetView(model: modelItem)
                view.leftTop = XY(0, topMark+W(16))
                topMark = view.bottom
                addSubview(view)
            }
        }
        
        height = topMark+getBottomSafeAreaHeight()+60
    }
}



// MARK: - 联系人信息内容 ItemView
class AuthContactContentItemView: UIView, CNContactPickerDelegate {
    
    var blockNamePhoneClick:((String, String) -> Void)?
    
    // MARK: - lazy
    lazy var imageBack: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.image = UIImage(named: "icon_face_bg")
        result.widthHeight = XY(W(345), W(276))
        return result
    }()
    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()
    lazy var viewRelation: SingleChoiceView = {
        let result = SingleChoiceView()
        return result
    }()
    lazy var viewPhone: SingleChoiceView = {
        let result = SingleChoiceView()
        result.blockChoiceClick = { [weak self] in
            guard let self = self else { return }
            GlobalMethod.isOpenContactPermissions { isOpen in
                DispatchQueue.main.async {
                    if isOpen { // 已允许权限
                        self.openContactPicker()
                    }
                }
            }
        }
        return result
    }()
    
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.widthHeight = XY(SCREEN_WIDTH, 0)
        self.backgroundColor = .clear
        
        self.addSubView()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 添加
    func addSubView() {
        addSubview(imageBack)
        imageBack.addSubview(labelTitle)
        imageBack.addSubview(viewRelation)
        imageBack.addSubview(viewPhone)
        resetView()
    }
    
    // MARK: - 事件
    func openContactPicker() {
        let picker = CNContactPickerViewController()
        picker.delegate = self
        // 获取当前最顶层的控制器来执行present
        if let topVC = GB_Nav?.topMostViewController() {
            topVC.present(picker, animated: true)
        } else {
            GB_Nav?.present(picker, animated: true)
        }
        // 上传通讯录联系人信息
        requestUploadAddressBookInfo()
    }
    
    // 选择联系人回调
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        // 获取联系人姓名
        let givenName = contact.givenName
        let familyName = contact.familyName
        // 全名
        let fullName = "\(givenName)\(isStr(givenName) && isStr(familyName) ? " " : "")\(familyName)"
        
        // 获取联系人电话号码
        var phoneArray: [ModelBtn] = []
        let phoneNumbers = contact.phoneNumbers
        for phoneNumber in phoneNumbers {
            let number = phoneNumber.value
            let phoneNumberString = number.stringValue
            
            var model = ModelBtn()
            model.title = phoneNumberString
            model.content = phoneNumberString
            phoneArray.append(model)
            print(" --- 电话 --- \(phoneNumberString)")
        }
        
        // 有数据才弹窗
        var phoneStr = ""
        if isAry(phoneArray) {
            // 联系人只有一个联系方式，直接填充该联系方式，不需要选了
            if let model = phoneArray.first {
                phoneStr = model.title ?? ""
            }
        }
        
        if isStr(phoneStr) && isStr(fullName) {
            let content = "\(UnPackStr(fullName))-\(UnPackStr(phoneStr))"
            viewPhone.showContent(content: content)
            if let block = blockNamePhoneClick {
                block(UnPackStr(fullName), UnPackStr(phoneStr))
            }
        } else {
            GlobalMethod.showAlert(strAlert: "Please select another contact, the phone or name is empty")
        }
        
        // 处理完毕后关闭通讯录控制器
        picker.dismiss(animated: true, completion: nil)
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        // 用户取消选择时的处理
        picker.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 重置界面
    func resetView(model: ModelAuthContactTeasingInfo = ModelAuthContactTeasingInfo()) {
        imageBack.centerXTop = XY(SCREEN_WIDTH/2, 0)
        labelTitle.resetView(
            title: UnPackStr(model.table),
            textColor: COLOR_WHITE(),
            font: UIFont.customExtraBoldFont(size: 20),
            shadowColor: UIColor(hex: "#4105A0"),
            outlineColor: UIColor(hex: "#3B0B9A")
        )
        labelTitle.centerXTop = XY(imageBack.width/2, W(20))
        
        var modelRelation =  ModelAuthPersonalItemInfo()
        modelRelation.whose = UnPackStr(model.closing)
        modelRelation.itself = UnPackStr(model.shut)
        modelRelation.pounding = UnPackStr(model.relationText)
        modelRelation.ages = model.farewell
        viewRelation.resetView(model: modelRelation)
        viewRelation.pickerView.titleStr = "Select Relationship"
        viewRelation.centerXTop = XY(imageBack.width/2, W(57));
        
        var modelPhone =  ModelAuthPersonalItemInfo()
        modelPhone.whose = UnPackStr(model.farmhouse)
        modelPhone.itself = UnPackStr(model.beyond)
        var phone = ""
        if isStr(model.cautiously) && isStr(model.racing) {
            phone = "\(model.cautiously)-\(model.racing)"
        }
        modelPhone.pounding = phone
        viewPhone.resetView(model: modelPhone)
        viewPhone.centerXTop = XY(imageBack.width/2, viewRelation.bottom);
        
        height = imageBack.bottom
    }
    
    // MARK: - 上报通讯录
    func requestUploadAddressBookInfo() {
        // 获取通讯里
        GlobalMethod.asyncBlock {
            GlobalMethod.getAddressBookArray { list in
                if(isAry(list)){
                    // 执行上传任务
                    HomeRequestApi.uploadAddressBook(list: list) { request, responseData in
                        
                    } failure: { request, error in
                        
                    }
                }
            }
        }
    }
}
